<template>
  <el-dialog :visible.sync="isShow" @close="close" width="70%" class="jiandingDialog" :show-close='false'
    :closeOnClickModal='false' append-to-body>
    <span slot="title" class="dialog-title">
      <span style="font-size:13px;margin-right:8px;">检定校准</span> {{checkRecordData.name}}
      <el-button size="mini" @click="close" class="popupClose">关闭</el-button>
    </span>
    <el-form label-width="110px" :inline="false" class="demo-form-inline jiandingForm" :model="uploadData" :rules="jiandingRules"
      ref="jiandingForm">
      <el-form-item label="校准日期" prop='executeDate'>
        <el-col :span="22">
          <el-date-picker v-model="uploadData.executeDate" style="width:100%;" :disabled="flag == 'look' || flag == 'shenhe'"
            size="mini" type="date" value-format="yyyy-MM-dd" placeholder="默认当前日期" :picker-options="pickerOptions">
          </el-date-picker>
        </el-col>
      </el-form-item>
      <el-form-item label="有效期" prop='expiryDate'>
        <el-col :span="22">
          <el-date-picker v-model="uploadData.expiryDate" style="width:100%;" size="mini" :disabled="flag == 'look' || flag == 'shenhe'"
            type="date" value-format="yyyy-MM-dd" placeholder="建议复校日期">
          </el-date-picker>
        </el-col>
      </el-form-item>
      <el-form-item label="校准单位" prop='checkUnit'>
        <el-col :span="22">
          <el-select filterable v-model="uploadData.checkUnit" style="width:100%;" :disabled="flag == 'look' || flag == 'shenhe'"
            placeholder="请选择" size='mini'>
            <el-option v-for="item in supplierList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-col>
      </el-form-item>
      <el-form-item label="审核人" prop='confirmMan'>
        <el-col :span="22">
          <el-select filterable v-model="uploadData.confirmMan" style="width:100%;" :disabled="flag == 'look' || flag == 'shenhe'"
            placeholder="请选择" size='mini'>
            <el-option v-for="item in EmployeeByLabs" :key="item.account" :label="item.name" :value="item.account">
            </el-option>
          </el-select>
        </el-col>
      </el-form-item>
      <el-form-item label="校准意见" prop='remark' style="width:100%;float:none;">
        <el-col :span="22">
          <el-input type="textarea" size="mini" :disabled="flag == 'look' || flag == 'shenhe'" placeholder="输入检定校准意见"
            v-model="uploadData.remark"></el-input>
        </el-col>
      </el-form-item>
    </el-form>
    <!--<div class="penalrow selectw100">
			<div class=" width100 ">
				<div class="inlineblock verticalmiddle informationItem" style="padding-top: 0;">
					<el-row v-if="flag=='new' || flag=='edit'">
						<input type="file" @change="getFile" multiple="multiple" id="jd-file" style='visibility: hidden;width: 0;height: 0;'>
						<span v-if="!totalFile">未选择文件</span>
						<el-row v-if="totalFile && $parent.$parent.userOpernation.download.display" v-for="(tag,index) in uploadData.files" :key="tag.name">
							<el-tag style="margin-top: 5px;" closable @close="removeTag(index)">
								{{tag.name}}
							</el-tag>
						</el-row>
					</el-row>
					<el-row v-if="flag=='look'||flag=='shenhe'" v-for="item in uploadData.files" :key="item.id">
						<el-button type="text" size="mini" @click="downLoadFile(item)" :key='item.id'>{{item.fileName}}</el-button>
					</el-row>
				</div>
			</div>
		</div>-->
    <div class="elTab">
      <el-tabs style="width: 100%;" v-model="activeName">
        <el-tab-pane label="电子报告" name="first">
          <el-row v-if="(flag=='new' || flag=='edit') && $parent.$parent.userOpernation.upload.display">
            <el-button type="primary" size="mini" @click="hcUpload" style="float:right;margin-bottom:5px;">上传</el-button>
            <input type="file" @change="getFile" multiple="multiple" id="jd-file" style='visibility: hidden;width: 0;height: 0;'>
          </el-row>
          <el-table :data="uploadData.files" style="width: 100%;height:calc(100% - 43px)" size="mini" class="tableCon">
            <el-table-column label="序号" min-width="50px">
              <template slot-scope="scope">
                {{scope.$index+1}}
              </template>
            </el-table-column>
            <el-table-column property="name" label="附件名称" key="file" v-if="flag=='new' || flag=='edit'" min-width="200px"
              :show-overflow-tooltip="true">
            </el-table-column>
            <el-table-column property="fileName" label="附件名称" key="file1" v-if="flag=='look'||flag=='shenhe'" min-width="200px"
              :show-overflow-tooltip="true">
            </el-table-column>
            <el-table-column label="操作" min-width="100px">
              <template slot-scope="scope">
                <el-button type="text" size="mini" @click="removeTag(scope.row,scope.$index)" v-if="flag=='new' || flag=='edit'">删除</el-button>
                <el-button type="text" size="mini" @click="downLoadFile(scope.row)" v-if=" (flag=='look'||flag=='shenhe')">下载</el-button>
                <el-button type="text" size="mini" @click="previewFile(scope.row)" v-if=" (flag=='look'||flag=='shenhe')">预览</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="审核信息" name="second" v-if="flag == 'look' || flag=='shenhe'">
          <div id="myIframe" v-if="reload" v-loading="loading1" style="text-align:center">
            <span style="color:#909399;line-height:100px;" v-if="WorkFlowMsg != '' && WorkFlowMsg != undefined">{{WorkFlowMsg}}</span>
            <iframe :src="url" id="workFlowIframe" ref="workFlowIframe" width="100%" height="100%" frameborder="0"
              scrolling="auto"></iframe>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>


    <span slot="footer" class="dialog-footer">
      <el-button v-if="flag=='shenhe'" class="penalButton" type="primary" size="mini" v-on:click="reviewFlowPop">审核</el-button>
      <el-button v-if="flag=='new' || flag=='edit'" class="penalButton" type="primary" size="mini" v-on:click="submitUpload"
        :disabled="!isRepeat">确定</el-button>
      <el-button class="penalButton" size="mini" v-on:click="close">取消</el-button>
    </span>
    <review-flow :addVisible.sync="reviewFlowShow" :reviewData="reviewData" :procInstType="procInstType" :reviewTitle="reviewTitle"
      @reloadMain="readAbility"></review-flow>
  </el-dialog>
</template>

<script>
  import {
    mapState
  } from 'vuex'
  const reviewFlow = () => import('@/common/reviewFlow.vue');

  export default {
    data() {
      return {
        reviewFlowShow: false, //审核流显示
        reviewData: null, //点击行需要审核的信息
        procInstType: 't_maintenance_record', //审核流要查的表
        reviewTitle: '检定校准审核',
        isShow: true,
        AuditArr: [],
        totalFile: null,
        uploadData: {
          equipment: this.util.date(),
          maintainType: 'MA02',
          executor: '',
          executeDate: '',
          files: [],
          confirmMan: '',
          remark: '',
        },
        // 设置当前日期之前的不可用
        pickerOptions: {
          disabledDate(time) {
            return time.getTime() > Date.now();
          }
        },
        jiandingRules: {
          confirmMan: [{
            required: true,
            message: '请选择审核人',
            trigger: 'change'
          }, ],
          expiryDate: [{
            required: true,
            message: '请选择校准日期',
            trigger: 'change'
          }, ],
          executeDate: [{
            required: true,
            message: '请选择有效期',
            trigger: 'change'
          }, ],
          remark: [{
            required: true,
            message: '请输入校准意见',
            trigger: 'blur'
          }, ],

        },
        isRepeat: true,
        activeName: "first",
        loading1: true,
        reload: true,
        url: "",
        WorkFlowMsg: "",
      }
    },
    computed: {
      ...mapState(['EmployeeByLabs', 'supplierList']),
      biaoyangTableHeight() {
        return ((window.innerHeight - 90) * 0.8 - 250)
      }
    },
    props: ['flag', 'rowData', 'checkRecordData'],
    components: {
      reviewFlow
    },
    created() {
      // this.getEmployeeByEquip()
    },
    mounted() {
      console.log(this.rowData)
      if (this.flag == 'edit') {
        if (this.rowData.status != 4) {
          this.rowData.remark = "";
        } else {
          for (var i in this.rowData.fileList) {
            this.rowData.fileList[i].name = this.rowData.fileList[i].fileName;
          }
          this.$set(this.uploadData, 'files', this.rowData.fileList)
        }
        this.$set(this.uploadData, 'id', this.rowData.id)
        this.$set(this.uploadData, 'fRef', this.rowData.fRef)
        this.$set(this.uploadData, 'equipment', this.rowData.equipment)
        this.$set(this.uploadData, 'executeDate', this.rowData.executeDate)
        this.$set(this.uploadData, 'executor', this.rowData.executor)
        this.$set(this.uploadData, 'expiryDate', this.rowData.expiryDate)
        this.$set(this.uploadData, 'remark', this.rowData.remark)
        this.$set(this.uploadData, 'confirmMan', this.rowData.confirmMan)
        this.$set(this.uploadData, 'name', this.rowData.name)
        this.$set(this.uploadData, 'checkUnit', this.rowData.checkUnit)


      } else {
        this.uploadData = Object.assign({}, this.uploadData, this.rowData)
        this.uploadData.files = JSON.parse(JSON.stringify(this.uploadData.fileList))

      }


    },
    watch: {
      activeName(val) {
        if (val == "second") {
          this.reload = true;
          if (process.env.NODE_ENV == 'development') {

            this.url = "../../static/workflow.html?id=" + this.uploadData.id + "&procInstType=" + this.procInstType +
              "&fromModel=look"

          } else {
            this.url = "static/workflow.html?id=" + this.uploadData.id + "&procInstType=" + this.procInstType +
              "&fromModel=look"

          }
          var that = this;
          // setTimeout(function () {
          // let iframe = document.getElementById("workFlowIframe");
          window.addEventListener('message', that.handleMessage1)
          // }, 3000)
        }
      }
    },
    methods: {
      handleMessage1(event) {
        const data = event.data
        console.log(data)
        switch (data.cmd) {
          case 'loadingHide':
            this.loading1 = false;
            this.WorkFlowMsg = "";
            break;
          case 'errorMsg':
            this.loading1 = false;
            this.WorkFlowMsg = "没有查询到审核信息"
            break;

        }
      },
      reviewFlowPop() {
        this.reviewFlowShow = true;
        this.reviewData = this.uploadData;
      },
      readAbility() {
        this.reviewFlowShow = false;
        this.$store.dispatch('getWorkflowList', 0).then(res => {
          this.$notify({
            showClose: true,
            message: '操作成功',
            type: 'success',
            title: "成功"
          })
        })
        this.close()
        this.$parent.init()
        this.$parent.$parent.readMaintenanceList()

      },
      getEmployeeByEquip() {
        console.log(this.rowData.equipmentId)
        var data = {}
        if (this.flag == 'look') {
          data.equipment = this.rowData.equipmentId
        } else {
          data.equipment = this.$parent.checkRecordData.equipmentId
        }
        this.$http({
          apiUrl: 'resource/getEmployeeByEquip.htm',
          method: 'post',
          isJson: false,
          params: data,

        }).then(res => {
          if (res.code === 0) {
            this.AuditArr = res.data
          }
        })
      },
      downLoadFile(item) {
        console.log(item)
        var url = "/download/fileDownload.htm"
        let token = sessionStorage.getItem('loginAccount')?sessionStorage.getItem('loginAccount'):undefined
        window.open(process.env.baseUrl + url + '?id=' + item.id + "&token=" + token);
      },
      hcUpload() {
        document.getElementById("jd-file").click()
      },
      submitUpload() {
        this.$refs.jiandingForm.validate((valid) => { //表单验证
          if (valid) {
            console.log(this.uploadData)
            if (this.uploadData.checkUnit == undefined) {
              this.uploadData.checkUnit = "";
            }
            if (this.uploadData.files.length == 0) {
              this.$notify({
                type: "warning",
                title: "警告！",
                message: "请上传文件！"
              })
              return;
            }
            console.log(this.uploadData.files)
            let params = this.formDating(this.uploadData);
            let url;
            if (this.flag == 'edit') {
              url = 'resource/updateMaintenanceRecord.htm'

            } else {
              url = 'resource/createMaintenanceRecord.htm'
            }
            // return;
            this.isRepeat = false;

            this.$http({
              apiUrl: url,
              method: 'post',
              params: params,
              headers: {
                'Content-Type': 'multipart/form-data'
              }
            }).then(res => {
              this.isRepeat = true;
              if (res.code === 0) {
                console.log(res)
                this.$notify({
                  showClose: true,
                  message: '执行成功！',
                  type: 'success',
                  title: "成功"
                })
                this.close()
                this.$parent.init()
                this.$parent.$parent.readMaintenanceList()
              }
            })

          } else {
            return false;
          }
        })

      },
      formDating(params) {
        console.log(params)
        let fromArr = params
        let $formData = new FormData();
        for (let j in fromArr) {
          if ((typeof fromArr[j]) == 'object') {
            for (let i of fromArr[j]) {
              $formData.append(j, i);
            }
          } else {
            $formData.append(j, fromArr[j]);
          }
        }
        return $formData
      },
      getFile($event) {
        let count = 0;
        for (let i of $event.target.files) {
          count = 0
          for (let j of this.uploadData.files) {
            if (i.name == j.name) {
              count += i.name
            }
          }
          if (count == 0) {
            this.uploadData.files.push(i)
          } else {
            this.$message({
              showClose: 'true',
              message: '重复添加，已过滤！',
              type: 'success'
            })
          }

        }
        this.totalFile = this.uploadData.files.length
        $event.target.value = "";
      },
      // 预览
      previewFile(row) {
        var url = "preview/fileToPdfPreview.htm"
        let token = sessionStorage.getItem('loginAccount')?sessionStorage.getItem('loginAccount'):undefined
        window.open(process.env.baseUrl + url + '?id=' + row.id + "&token=" + token);
      },

      close() {
        this.isRepeat = true;
        this.$parent.tianjiajiandingjiluShow = false;
        this.activeName = "first";
        this.loading1 = true;
        this.reload = false;
        this.WorkFlowMsg = "";
      },
      removeTag(row, index) {
        if (row.hasOwnProperty('id')) {
          this.$confirm('确定要删除已上传的文件吗', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.$http({
              method: 'post',
              apiUrl: '/download/fileDelete.htm',
              params: {
                id: row.id,
              },
              isJson: false,
            }).then(res => {
              if (res.code === 0) {
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                });
                this.uploadData.files.splice(index, 1)
              }
            })
          })
        } else {
          this.uploadData.files.splice(index, 1)
        }
      },
      addbyx() {
        this.tableData6.push({
          baoyangxiang: ''
        })
      },
      deletebyx(index) {
        this.tableData6.splice(index, 1)
      }
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style>
  .jiandingDialog .el-dialog {
    margin-top: 10vh !important;
    height: 80%;
  }

  .jiandingDialog .el-dialog .el-dialog__body {
    height: calc(100% - 85px);
    padding: 15px;
  }

  .jiandingDialog .jiandingForm {
    height: 185px;
  }

  .jiandingDialog .jiandingForm .el-form-item {
    margin-bottom: 15px;
    display: inline-block;
    width: 48%;
  }

  .jiandingDialog .el-dialog .elTab {
    clear: both;
    height: calc(100% - 185px)
  }

  .jiandingDialog .el-dialog .elTab .el-tabs {
    height: 100%
  }

  .jiandingDialog .el-dialog .elTab .el-tabs .el-tabs__content {
    height: calc(100% - 40px)
  }

  .jiandingDialog .el-dialog .elTab .el-tabs .el-tabs__content .el-tab-pane {
    height: 100%
  }
</style>
